<?php 
class log{
	private $filename_template = "log_?.log";
	private $filename_pattern = "Y-m-d";
	private $dateformat = "Y-m-d H:i:s";
	private $handle = null;
	private $logdir = null;
	private $logfile = null;
	private $log = null;
	
	public function __construct($logdir="./logs",$log=true){
		$this->logdir = $logdir;
		$this->log = $log;
		$this->logfile = $logdir."/".$this->filename_build();
	}
	
	public function log_delete($date){
		$success = false;
		if($date){
			$file = $this->logdir."/"."log_".$date.".log";
			if($file==$this->logfile){
				$this->close();
			}
			$success = unlink($file);
		}
		return false;
	}
	public function log_get($date){
		if($date){
			$file = $this->logdir."/"."log_".$date.".log";
			if(file_exists($file)){
				$content = file_get_contents($file);
				return $content;
			}
		}
		return null;
	}
	private function filename_build(){
		$replace = date($this->filename_pattern);
		$logfile = str_replace("?", $replace, $this->filename_template);
		return $logfile;
	}
	
	private function open(){
		if(!$this->handle){
			$this->handle=fopen($this->logfile, "a");
		}
	}
	private function close(){
		if($this->handle){
			fclose($this->handle);
		}
		$this->handle=null;
	}
	public function log($message,$type=null){
		if($this->log){
			$this->open();
			$output = "[".date($this->dateformat)."] ";
			if($type){
				$output.="[$type]";
			}
			$output .=$message."\n";
			fwrite($this->handle, $output);
		}
	}
	public function debug($message){
		if($this->log){
			$this->open();
			$this->log($message,"DEBUG");
		}
	}
	public function warn($message){
		if($this->log){
			$this->open();
			$this->log($message,"WARN");
		}
	}
	public function error($message){
		if($this->log){
			$this->open();
			$this->log($message,"ERROR");
		}
	}
	public function __destruct(){
		$this->close();
	}
}
?>